package g101

import (
	"time"

	"engine/log"
	"gitee.com/ameise84/e3utils/utils"
	"servers/app/client/conn"
	"servers/app/client/misc"
	"servers/app/client/protos/relay"
	"servers/models/error_code"
	"servers/models/protos/google/pb/net_protos/games/pb101"
)

func AutoTest(c conn.Client, msgCount int, sleepMs int) {
	c.SetServerID(101)
	rspScene := GameSceneReq(c)
	if misc.IsErrorCode(rspScene.Code) {
		return
	}
	freeTime := rspScene.Scene.FreeTimes
	betIndex := rspScene.Scene.DefaultBetIndex
	betScore := rspScene.Cfg.BetScore[betIndex]

	for i := 0; i < msgCount || msgCount == -1; i++ {
		req := &pb101.GameBetReq{BetKind: utils.IfThenElse(freeTime > 0, pb101.BetKind_Bet, pb101.BetKind_Free), BetIndex: betIndex, BetScore: betScore}
		rspBet := GameBetReq(c, req)
		if misc.IsErrorCode(rspBet.Code) {
			if rspBet.Code != error_code.ErrorCodePlayerScoreNotEnough {
				return
			}
			relay.Recharge(c, betScore*100000)
			continue
		}
		freeTime = rspBet.CurFree.After
		time.Sleep(time.Duration(sleepMs) * time.Millisecond)
	}
	log.GetLogger().Debug("run over").Int("tims", msgCount).Object(c).Println()
}

func GameSceneReq(c conn.Client) *pb101.GameSceneRsp {
	c.SetServerID(101)
	rsp := &pb101.GameSceneRsp{
		Code: error_code.ErrorCodeUnknown,
	}
	if err := c.Send(&pb101.GameSceneReq{}, rsp); err != nil {
		log.GetLogger().Error(err.Error()).Object(c).Println()
	}
	return rsp
}

func GameBetReq(c conn.Client, req *pb101.GameBetReq) *pb101.GameBetRsp {
	c.SetServerID(101)
	rsp := &pb101.GameBetRsp{
		Code: error_code.ErrorCodeUnknown,
	}
	if err := c.Send(req, rsp); err != nil {
		log.GetLogger().Error(err.Error()).Object(c).Println()
	}
	return rsp
}
